<template>
	<div>
		<el-dialog title="添加类型" :visible.sync="addVisible" width="30%" :before-close="closeAddClassify">
			<el-form :model="classifyList" ref="addClassify" label-width="100px">
        <el-form-item label="类型名称" prop="classifyName" :rules="[
              { required: true, message: '请输入类型名称', trigger: 'blur' },
            ]">
        	<el-input type="text" v-model="classifyList.classifyName" placeholder="请输入用户名"></el-input>
        </el-form-item>

				<el-form-item label="类型图片" prop="classifyImg" :rules="[
              { required: true, message: '请插入图片', trigger: 'blur' },
            ]">
          <el-input v-show="false" v-model="classifyList.classifyImg"/>
					<!-- <el-input type="text" v-model="classifyList.classifyImg" placeholder="请输入持有人姓名" clearable></el-input> -->
          <el-upload
            class="upload-demo"
            ref="upload"
            list-type="picture"
            action=""
            :limit="1"
            :on-change="imgVaildata"
            :auto-upload="false"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-upload="beforeUploadHandle"
            :http-request="handleUploadForm"
            >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <!-- <el-button style="margin-left: 10px;" size="small"  @click="submitUpload">上传到服务器</el-button> -->
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          <!-- <input type="file" name="photo"><br> -->
        </el-form-item>

        <el-form-item label="类型/文章" prop="classifyType" :rules="[
             { required: true, message: '请选择权限', trigger: 'blur' },
           ]">
          <el-select v-model="classifyList.classifyType" placeholder="可选查询项" :default-first-option="true" @change="typeJudge(classifyList.classifyType)">
            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="文章内容" v-if="showArticle">
          <el-input type="textarea" v-model="classifyList.articleDetail" autosize></el-input>
        </el-form-item>

        <el-form-item label="显示状态" prop="indexShow" :rules="[
              { required: true, message: '请选择是否启用', trigger: 'blur' },
            ]">
          <el-switch
            v-model="classifyList.onstatus" @change="onstatus(classifyList.onstatus)"
            active-text="启用" inactive-text="禁用">
          </el-switch>
        </el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="closeAddClassify">取 消</el-button>
				<el-button type="primary" @click="submitUpload('addClassify')">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		name: "",
		props: ["addVisible"],
		data() {
			return {
        showArticle:false,
				classifyList: {
					classifyName: "",
          classifyImg:"",
          classifyType:0,
          articleDetail:"",
          //role在数据库的默认值为1，所以直接显示内容即可，不需要通过内容判断转值
          //以下两个变量用于判断用户状态
          indexShow:0,
          onstatus:false,
				},
        typeList:[{
          value:0,
          label: '类型'
        },{
          value:1,
          label: '文章'
        }],
			}
		},
		methods: {
      //清空图片方法
      clearFiles () {
          this.$refs['upload'].clearFiles();
      },
      //验证图片是否为空
      imgVaildata(file, fileList){
          var self = this
          console.log('vue 图片上传钩子函数')
          self.classifyList.classifyImg=file.name
          console.log(self.classifyList.classifyImg)
          if(file.name==null || file.name==""){
            self.classifyList.classifyImg=null
          }
      },
      //查询当前添加的是否是文章，文章可以添加文章内容
      typeJudge(judgeType){
         if(judgeType===1){
           this.showArticle=true
         }else{
           this.showArticle=false
           this.classifyList.articleDetail=""
         }
      },
       //需要等待dialog 打开完毕后 在金数据渲染
       //设置权限下拉框的默认值
       opendEnd(){
       },
       //设置是否显示状态
       onstatus(onstatus){
         console.log(onstatus)
         if(onstatus===true){
           this.classifyList.indexShow=1
         }else if(onstatus===false){
           this.classifyList.indexShow=0
         }
         // console.log(this.manager.onstatus)
         // console.log(this.manager.status)
       },
       //清除文本框数据，返回相对应文本框的值
       clearData(){
           this.classifyList={
             classifyName: "",
             classifyImg:"",
             classifyType:0,
             articleDetail:"",
             //以下两个变量用于判断用户状态
             indexShow:0,
             onstatus:false,
           }
           this.showArticle=false
           this.clearFiles()
       },
       //设置关闭添加页面方法
      closeAddClassify() {
          this.clearData()
      		this.$parent.addVisible = false
      },
      /* */
      //判断表单数据是否为空
      //并提交数据
     submitUpload(params) {
       console.log("触发判断事件")
       var self = this
       this.$refs[params].validate((valid) => {
      	if (valid) {
          // if(params.file){
            self.$refs.upload.submit();
          // }else{
          //   self.handleUploadForm()
          // }
      	} else {
      		console.log('error submit!!');
      		return false;
      	}
      });
     },
     //触发删除事件
     handleRemove(file, fileList) {
       console.log("触发删除事件")
       if(file){
         this.classifyList.classifyImg=""
       }
       console.log(file, fileList);
     },
     handlePreview(file) {
       console.log("kukukuku")
       console.log(file);
     },
     /* */
      //上传文件前执行的方法,判断文件格式
      beforeUploadHandle(file) {
        console.log("执行上传前方法")
        if (
            file.type !== "image/png" &&
            file.type !== "image/jpeg"
        ) {
          this.$message.error("只支持.jpg、.jpeg、.jpe、.png文件！");
          return false;
        }
      },
      //执行添加方法
      handleUploadForm(param) {
        console.log(param)
        console.log(JSON.stringify(this.classifyList))
        let self = this
        var onlineManager = JSON.parse(sessionStorage.getItem("manager"))
        var page = sessionStorage.getItem("page")
        // 检测输入的数据中是否存在空格
        var classifyName = this.classifyList.classifyName
        var ifArticle = this.classifyList.classifyType
        if(ifArticle!=1){
          this.classifyList.articleDetail=""
        }
        if(classifyName.split(" ").length==1){
          let formData = new FormData()
          // 在formData中加入我们需要的参数
          formData.append('file', param.file)
          formData.append('classify', JSON.stringify(this.classifyList))
          console.log("开始向后端发送请求")
          // 向后端发送数据
          self.$http.post('/api/CakeShop/DataManage/addClassify', formData).then((res) => {
            console.log(123123)
            // if (res.status === 200) {
            //   thisInfo.$message.success('修改信息成功')
            // } else {
            //   thisInfo.$message.success('修改信息失败')
            // }
            // thisInfo.formFileList = []
            // thisInfo.uploadFormFileList = []
            console.log(res)
            //判断数据是否存在
            if(res.data.exist===0){
              if (res.data.addSuccNum>0) {
                self.$message({
                  message: res.data.msg,
                  type: 'success',
                  onClose: function() {
                    //添加完毕后清楚文本框中内容
                    self.clearData()
                    //关闭修改界面
                    self.closeAddClassify()
                    //添加完数据返回首页
                    self.$parent.getMemberList(page)
                  }
                });
              }else{
                self.$message({
                  duration: 1500,
                  message: res.data.msg,
                  type: "error",
                  onClose: function() {
                    self.loading = false;
                  },
                });
              }
            }else{
              self.$message({
              	duration: 1500,
              	message: res.data.msg,
              	type: "error",
              	onClose: function() {
              		self.loading = false;
              	},
              });
            }
          })
        }else{
          self.$message({
            duration: 1500,
            message: "用户名中存在非法字符空格!",
            type: "error",
            onClose: function() {
              self.loading = false;
            },
          });
        }
      },
		}
	}
</script>
<style>
</style>
